<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        label-position="right"
        label-width="70px"
        onsubmit="return false"
      >
        <el-col :span="6">
          <el-form-item label="用电企业">
            <el-select
              @change="companyChange"
              style="width: 100%"
              v-model="form.companyId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="text-align: left; padding-left: 20px">
          <el-radio-group v-model="radio" style="margin-right: 20px">
            <el-radio-button label="日"></el-radio-button>
            <el-radio-button label="月"></el-radio-button>
            <el-radio-button label="年"></el-radio-button>
          </el-radio-group>
          <el-date-picker
            style="width: 200px; height: 40px; line-height: 40px"
            v-model="date"
            :type="
              this.radio == '日'
                ? 'date'
                : this.radio == '月'
                ? 'month'
                : 'year'
            "
            :format="
              this.radio == '日'
                ? 'yyyy-MM-dd'
                : this.radio == '月'
                ? 'yyyy-MM'
                : 'yyyy'
            "
            placeholder="选择时间"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-form-item>
            <div>
              <button
                @click="chongzhi"
                class="button"
                style="margin-right: 5px"
              >
                重置
              </button>
              <button @click="chaxun" class="button chaxun">查询</button>
            </div>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="top">
        <div class="left" v-loading="loading1">
          <div class="tit">用电构成</div>
          <div style="height: 100%; border-right: 1px solid #ccc">
            <div v-if="e1" id="ydgc" style="width: 100%; height: 100%"></div>
          </div>
        </div>
        <div class="right" v-loading="loading2">
          <div class="tit">用能趋势</div>
          <div v-if="e2" id="ynqs" style="width: 100%; height: 90%"></div>
        </div>
      </div>
      <div class="bottom">
        <div class="top2">
          <div class="tit2">同环比分析</div>
          <div class="tabs">
            <span>
              <button
                class="button"
                @click="exporttab"
                style="margin-right: 20px"
              >
                导出
              </button>
              <i
                @click="isshow = 'echart'"
                :style="{
                  color: isshow === 'echart' ? '#007cee' : '#000',
                  'margin-right': '10px'
                }"
                class="iconfont icon-zhuzhuangtutubiao"
              ></i>
              <i
                @click="isshow = 'table'"
                :style="{
                  color: isshow === 'table' ? '#007cee' : '',
                  'margin-right': '10px'
                }"
                class="iconfont icon-biaoge"
              ></i>
            </span>
          </div>
        </div>
        <div
          v-loading="loading3"
          v-if="isshow === 'echart'"
          style="width: 100%; height: 90%"
        >
          <div v-if="e3" id="thbfx" style="width: 100%; height: 90%"></div>
        </div>
        <div v-show="isshow == 'table'" class="fartab">
          <el-table
            v-loading="loading4"
            :data="ComparisonList"
            style="width: 99%"
            height="35vh"
            border
            ref="table"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="100px"
            >
            </el-table-column>
            <el-table-column align="center" prop="dateTime" label="日期">
            </el-table-column>
            <el-table-column prop="departmentName" label="部门">
            </el-table-column>
            <el-table-column
              align="right"
              prop="usageValue"
              label="本期能耗(kWh)"
            >
            </el-table-column>
            <el-table-column
              align="right"
              prop="lastMonthValue"
              label="上月同期能耗(kWh)"
            >
            </el-table-column>
            <el-table-column
              align="right"
              prop="lastYearValue"
              label="去年同期能耗(kWh)"
            >
            </el-table-column>
            <el-table-column align="right" prop="hbRatio" label="环比(%)">
            </el-table-column>
            <el-table-column align="right" prop="tbRatio" label="同比(%)">
            </el-table-column>
          </el-table>
          <!-- 底部分页 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getCompanyListApi } from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import dayjs from 'dayjs'
import {
  getComparisonLineApi,
  getComparisonListApi,
  getUsageLineApi,
  getUsagePieApi
} from '@/api/energy-consumption/Department/Analysis'
import { exportexcel } from '@/utils/excel'
export default {
  name: 'DepartmentAnalysis',
  data() {
    return {
      radio: '日',
      form: {},
      ComparisonList: [],
      date: null,
      isshow: 'echart',
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      companyList: [],
      UsagePieList: [],
      UsageLineList: [],
      ComparisonLineList: [],
      ProportionData: {},
      e1: true,
      e2: true,
      e3: true
    }
  },
  watch: {
    radio: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs().format('YYYY-MM-DD')
        } else if (this.radio === '月') {
          this.date = dayjs().format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs().format('YYYY')
        }
      },
      immediate: true
    },
    isshow: {
      async handler(newValue) {
        if (this.isshow === 'echart') {
          this.getComparisonLine().then(() => this.myChart3())
        } else {
          this.getComparisonList()
        }
      }
    },
    date: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs(newValue).format('YYYY-MM-DD')
        } else if (this.radio === '月') {
          this.date = dayjs(newValue).format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs(newValue).format('YYYY')
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    await this.getCompanyList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      if (val) {
        localStorage.setItem('companyId', val)
      }
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi()
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.$set(this.form, 'companyId', companyId)
      } else {
        this.$set(this.form, 'companyId', this.companyList[0].id)
      }
    },
    // 初始化
    async getchushihua() {
      this.radio = '日'
      this.isshow = 'echart'
    },

    // 部门能耗分析-用电构成
    async getUsagePie() {
      this.e1 = false
      this.loading1 = true
      const res = await getUsagePieApi({
        companyId: this.form.companyId,
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      console.log(res)
      this.UsagePieList = res.data?.list
      // this.ProportionData = res.data.entity
      this.e1 = true
      this.loading1 = false
    },

    // 设备能耗趋势
    async getUsageLine() {
      this.e2 = false
      this.loading2 = true
      const res = await getUsageLineApi({
        companyId: this.form.companyId,
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      console.log(res)
      this.UsageLineList = res.data.list
      this.e2 = true
      this.loading2 = false
    },

    // 同环比曲线
    async getComparisonLine() {
      this.e3 = false
      this.loading3 = true
      const res = await getComparisonLineApi({
        companyId: this.form.companyId,
        dateType: this.radio === '日' ? '1' : this.radio === '月' ? '2' : '3',
        dateString: this.date
      })
      console.log(res)
      this.ComparisonLineList = res.data.list
      console.log('ComparisonLineList', this.ComparisonLineList)

      this.e3 = true
      this.loading3 = false
    },
    // 表格
    async getComparisonList() {
      this.e4 = false
      this.loading4 = true
      const res = await getComparisonListApi({
        companyId: this.form.companyId,
        dateString: this.date,
        dateType: this.radio === '日' ? '1' : this.radio === '月' ? '2' : '3'
      })
      this.ComparisonList = res.data.list
      this.e4 = true
      this.loading4 = false
    },
    exporttab() {
      exportexcel(
        '/ecm-microservice-biz/ecm/department/energy/analysis/data/comparison/exportExcel',
        {
          dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
          dateString: this.date,
          companyId: this.form.companyId
        },
        '部门能耗分析'
      )
    },
    // 获取数据
    async getdatalist() {
      const promises = [
        this.getUsagePie().then(() => this.myChart1()),
        this.getUsageLine().then(() => this.myChart2()),
        this.getComparisonLine().then(() => {
          if (this.isshow === 'echart') {
            this.myChart3()
          }
        })
      ]
      this.getComparisonList()

      // 等待所有Promise完成
      await Promise.all(promises)
    },
    myChart1() {
      const data1 =
        this.UsagePieList?.length > 0
          ? this.UsagePieList.map((i) => {
              return {
                name: i.timeReading,
                value: i.valueReading
              }
            })
          : []

      const myChart1 = echarts.init(document.getElementById('ydgc'))
      myChart1.setOption({
        legend: {
          orient: 'vertical', // 设置legend垂直排列
          right: 70,
          top: 'center'
          // data: data1.map((i) => i.name)
        },
        series: [
          {
            type: 'pie',
            center: ['45%', '50%'],
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            label: {
              show: false,
              position: 'center'
            },
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            labelLine: {
              show: false
            },
            data: data1
          }
        ]
      })

      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart1.resize()
      })
    },

    myChart2() {
      const series = this.UsageLineList.map((obj) => {
        return {
          name: obj.name,
          type: 'bar',
          stack: 'department',
          emphasis: {
            focus: 'series'
          },
          data: obj.datalist.map((i) => {
            return [i.timeReading, i.valueReading]
          })
        }
      })
      console.log(series)
      const time = this.UsageLineList.map((item) =>
        item.datalist.map((data) => data.timeReading)
      ).flat()
      console.log('time', time)
      const myChart2 = echarts.init(document.getElementById('ynqs'))

      myChart2.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category'
          // data: time
        },
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: series
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart2.resize()
      })
    },

    myChart3() {
      // const data = [
      //   {
      //     name: '运营部',
      //     datalist: [
      //       { name: '当期', valueReading: 666 },
      //       { name: '同期', valueReading: 888 },
      //       { name: '去年同期', valueReading: 999 }
      //     ]
      //   },
      //   {
      //     name: '市场部',
      //     datalist: [
      //       { name: '当期', valueReading: 333 },
      //       { name: '同期', valueReading: 444 },
      //       { name: '去年同期', valueReading: 555 }
      //     ]
      //   }
      // ]
      const data1 = {
        name: '当前',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        barGap: 0,
        data: this.ComparisonLineList.map((i) => {
          return i.datalist[0].valueReading
        })
      }
      const data2 = {
        name: '去年同期',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        barGap: 0,
        data: this.ComparisonLineList.map((i) => {
          return i.datalist[1].valueReading
        })
      }
      const data3 = {
        name: '上个月同期',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        barGap: 0,
        data: this.ComparisonLineList.map((i) => {
          return i.datalist[2]?.valueReading
        })
      }
      console.log('data1', data1)
      const myChart3 = echarts.init(document.getElementById('thbfx'))
      myChart3.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data:
            this.radio === '年'
              ? ['当前', '去年同期']
              : ['当前', '去年同期', '上个月同期']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.ComparisonLineList.map((i) => i.name)
        },
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: this.radio === '年' ? [data1, data2] : [data1, data2, data3]
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart3.resize()
      })
    },

    chaxun() {
      this.getdatalist()
    },

    async chongzhi() {
      await this.getchushihua()
      this.getdatalist()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}

.option {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.tit {
  display: flex;
  align-items: center;
  padding-left: 20px;
  margin-top: 10px;
  font-weight: bold;
  img {
    margin-right: 10px;
  }
}

.bigbox {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f1f1f1;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    margin-bottom: 10px;
    // transition-property: all;
    // transition-duration: 0.2s;

    .button {
      width: 63px;
      height: 32px;

      background-color: #fff;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
    .chaxun {
      background-color: #1890ff;
      color: #fff;
    }
  }
  .bodybox {
    flex: 1;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      height: 45%;
      width: 100%;
      .left {
        background-color: #fff;
        width: 30%;
      }
      .right {
        flex: 1;
        background-color: #fff;
      }
    }
    .bottom {
      flex: 1;
      background-color: #fff;
      padding: 0 20px;
      .top2 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        .tit2 {
          display: flex;
          align-items: center;

          font-weight: bold;
          img {
            margin-right: 10px;
          }
        }
        .tabs {
          .button {
            width: 60px;
            height: 32px;
            background-color: #1a90fe;
            color: #fff;
            border-radius: 3px;
            border: none;
          }
          i:hover {
            color: #2194ff;
            cursor: pointer;
          }
        }
      }
    }
  }
}

::v-deep .el-form-item {
  width: 100%;
  margin-left: -10px;
}

::v-deep .el-form-item__content {
  width: calc(100% - 100px);
}
::v-deep .el-col-6 {
  height: 40px;
  text-align: right;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep.el-form--inline {
  height: 100% !important;
  box-sizing: border-box;
}
::v-deep .el-radio-button__inner {
  padding: 8px 20px;
}
::v-deep .el-input__icon {
  line-height: 20px;
}
button {
  cursor: pointer;
}
</style>
